package com.supplychain.scm.core.common.version;

import com.supplychain.scm.core.basis.constant.CommonConstants;
import com.supplychain.scm.core.common.version.enums.ApiVersionExceptionType;
import com.supplychain.scm.core.common.version.enums.ClientType;
import lombok.Data;
import org.springframework.util.StringUtils;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName ApiVersionItem
 * @createTime 12:11:00 2023/01/05
 */
@Data
public class ApiVersionItem implements Comparable<ApiVersionItem> {

    private static final String SPLIT = "\\.";

    private ClientType[] clientTypes;

    private int x;

    private int y;

    private int z;

    public static ApiVersionItem converter(String version, ClientType[] clientTypes) {
        if (!StringUtils.hasText(version)) {
            return null;
        }
        ApiVersionItem apiVersionItem = new ApiVersionItem();
        apiVersionItem.clientTypes = clientTypes;
        String[] strings = version.split(SPLIT);
        int length = strings.length;
        apiVersionItem.setX(parse(strings[CommonConstants.ZERO]));
        if (length == CommonConstants.TWO.intValue()) {
            apiVersionItem.setY(parse(strings[CommonConstants.ONE]));
        } else if (length == 3) {
            apiVersionItem.setY(parse(strings[CommonConstants.ONE]));
            apiVersionItem.setZ(parse(strings[CommonConstants.TWO]));
        } else if (length > 3) {
            throw new ApiVersionException(ApiVersionExceptionType.LENGTH);
        }
        return apiVersionItem;
    }

    private static int parse(String i) {
        try {
            return Integer.parseInt(i);
        } catch (NumberFormatException e) {
            throw new ApiVersionException(ApiVersionExceptionType.FORMAT);
        }
    }

    @Override
    public int compareTo(ApiVersionItem o) {
        if (o == null) {
            return -1;
        }
        int code = x - o.x;
        if (code != 0) {
            return code;
        }
        code = y - o.y;
        if (code != 0) {
            return code;
        }
        return z - o.z;
    }
}
